const http = require('http');
const shell = require('shelljs');
const querystring = require('querystring');
let cmd = ['cd ~/web-service/mock', 'git fetch origin master', 'git reset --hard origin/master', 'npm install', 'pm2 restart mock']
http.createServer(function (req, res) {
    if (!shell.which('git')) {
        shell.echo('Sorry, this script requires git');
        shell.exit(1);
        res.statusCode = 500;
        res.write("err");
        res.end();
        return false;
    }
    if (req.url === '/gitlistener/mock' && req.headers['x-gitlab-token'] === 'mockmock666') {
        let alldata = ''
        req.on('data', function(chunk){
            alldata += chunk;
        })
        req.on('end', function(){
            let str = alldata.toString()
            let obj = querystring.parse(str)
            if(obj.ref === 'refs/heads/master') {
                if(shell.exec(cmd.join('&&')).code === 0) {
                    res.write("ok");
                    res.end();
                } else {
                    res.write("部署命令执行出错");
                    res.end();
                }
            } else {
                res.write("not master");
                res.end();
            }
        })

    } else {
        res.statusCode = 400;
        res.write("err")
        res.end()
        return false;
    }
}).listen(7362)
